<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/3
 * Time: 10:29
 */

namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Log;
use think\Session;

class Wxpay extends Base {
    //初始化
    public function _initialize(){
        //php 判断http还是https
        $this->http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        vendor('WeiXinpay.wxpay');
    }
    //北美玩乐小程序支付
    public function index(){
         header("Content-Type: text/html;charset=utf-8");
         $data  = $this->request->post();
         $price = $data['price'];
         $order_no  = $data['order_no'];
         $openid    = $data['openid'];
         $pay_sn = trim($order_no);
         if (!$pay_sn) {
             echo json_encode(array('code'=>0,'msg'=>'支付信息错误！'));
             exit();
         }
         $order_info =Db::name('order')->where(['order_no'=>$pay_sn])->find();
         if (!$order_info) {
             echo json_encode(array('code'=>0,'msg'=>'没有找到支付订单！'));
             exit();
         }
         $goods=Db::name('goods')->where(['goods_id'=>$order_info['goods_id']])->find();
         $use=Db::name('member')->where(['program_openid'=>$openid])->find();
         if ($use['member_status']==2) {
             echo json_encode(array('code'=>0,'msg'=>'该用户已禁用！'));
             exit();
         }
         $total_fee=$price*100;
         //②、统一下单
         $input = new \WxPayUnifiedOrder();
         $input->SetBody('快帮行商城商品购买');
         $input->SetOut_trade_no($pay_sn.'KBX'.time());
         $input->SetTotal_fee($total_fee);
         $input->SetTime_start(date("YmdHis"));
         $input->SetTime_expire(date("YmdHis", time() + 1800));
         $input->SetGoods_tag("快帮行商城商品购买_".$goods['goods_name']);
         $input->SetTrade_type("JSAPI");
         $input->SetOpenid($openid);

         //非自定义appid 【系统默认北美玩乐小程序】
         $customize = false;
         $input->SetNotify_url('https://c.kuaibangxing.com/api/Notify/notify');
         $order = \WxPayApi::unifiedOrder($input,6,$customize);

         $timeStamp=(string)time();
         $array=array(
                "appId"=>$order['appid'],
                "timeStamp"=>$timeStamp,
                "nonceStr"=>$order['nonce_str'],
                "package"=>"prepay_id=".$order['prepay_id'],
                "signType"=>'MD5',
         );
         $buff=$this->MakeSign($array);
         $string=$buff.'&key='.'kuaibangxing12345678911111111111';
         $str=MD5($string);
         $sign=strtoupper($str);
         //重新生成签名
         $array['sign']=$sign;
         $array['partnerid']=$order['mch_id'];
         $array['prepay_id']=$order['prepay_id'];
         echo json_encode(array('code'=>0,'msg'=>'','data'=>$array));
         exit();
     }
    //拼游小程序支付
    public function group(){
        header("Content-Type: text/html;charset=utf-8");
        $data  = $this->request->post();
        $order_no  = $data['order_no'];
        $openid    = $data['openid'];
        $wxsoft    = $data['wxsoft']??"beimei";
        $pay_sn = trim($order_no);
        if (!$pay_sn) {
            echo json_encode(array('code'=>0,'msg'=>'支付信息错误！'));
            exit();
        }
        $kbxToken = new KbxToken();
        $order_info = (new KbxOrder())->kbx_order_by_no($pay_sn);
        $order_info = $kbxToken->object_array($order_info);
        log::log('订单信息：'.json_encode($order_info));
        if(!empty($res['msg'])) return json_encode(['code'=>-400,'msg'=>$res['msg']]);
        //支付状态判定
        $orderStatus = $order_info['orderStatusForUser']??$order_info['status']['orderStatus'];
        $paymentStatus = $order_info['status']['paymentStatus'];
        $orderStatus = (new KbxOrder())->getStatusByOrderStatus($orderStatus,$paymentStatus);
        $displayedStatusStr = (new KbxOrder())->getDisplayOrderStateTitle($orderStatus,$paymentStatus);
        if($orderStatus > 1) return json_encode(['code'=>-400,'msg'=>'当前订单状态为'.$displayedStatusStr.',不能支付']);
        if($wxsoft=='grouptour'){
            $use = db('member')->where(['grouptour_openid'=>$openid])->find();
        }else{
            $use = db('member')->where(['program_openid'=>$openid])->find();
        }
        if ($use['member_status']==2) {
            echo json_encode(array('code'=>0,'msg'=>'该用户已禁用！'));
            exit();
        }
        //获取支付金额
        $price = $order_info['price']['amount']??0;
        if($price <= 0) return json_encode(['code'=>-400,'msg'=>'订单金额小于0，不能支付']);
        $total_fee = $price*100;
        //设置支付标题
        $product_name = $order_info['carPoolOrder']['name']??'';
        $body = '快帮行拼游产品报名';
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetOut_trade_no($pay_sn.'KBX'.time());
        $input->SetTotal_fee("$total_fee");
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 1800));
        $input->SetGoods_tag($body."_".$product_name);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $input->SetAttach($wxsoft);
        if(!empty($wxsoft)){
            if($wxsoft=='beimei'){
                $wxConfig = config('WxConfig.beimei');
            }else{
                $wxConfig = config('WxConfig.gtour');
            }
            //自定义appid mchid
            $customize = true;
            $input->SetAppid($wxConfig['appid']);
            $input->SetMch_id($wxConfig['mchid']);
        }else{
            $customize = false;
        }
        //设置回调地址
        $notifyUrl = 'https://h.kuaibangxing.com/api/Notify/notify';
        $input->SetNotify_url($notifyUrl);
        $order = \WxPayApi::unifiedOrder($input,6,$customize);
        if(!empty($order['return_code']) && $order['return_code']=='FAIL'){
            return json_encode(['code'=>-400,'msg'=>$order['return_msg']]);
        }
        $timeStamp=(string)time();
        $array=array(
            "appId"=>$wxConfig['appid'],
            "timeStamp"=>$timeStamp,
            "nonceStr"=>$order['nonce_str'],
            "package"=>"prepay_id=".$order['prepay_id'],
            "signType"=>'MD5'
        );
        $buff=$this->MakeSign($array);
        $string=$buff.'&key='.'kuaibangxing12345678911111111111';
        $str=MD5($string);
        $sign = strtoupper($str);
        //重新生成签名
        $array['sign']=$sign;
        $array['partnerid']=$order['mch_id'];
        $array['prepay_id']=$order['prepay_id'];
        return json_encode([
            'code'=>200,
            'msg'=>'success',
            'data'=>$array
        ]);
    }
    //微信返回数据
    public function notify(){
        /*$notify = new \PayNotifyCallBack();
        $notify->Handle(false);*/

        $res_xml = file_get_contents("php://input");
        libxml_disable_entity_loader(true);
        $ret = json_decode(json_encode(simplexml_load_string($res_xml,'simpleXMLElement',LIBXML_NOCDATA)),true);

        $path = "./Data/log/";
        if (!is_dir($path)){
            mkdir($path,0777);  // 创建文件夹test,并给777的权限（所有权限）
        }
        $content = date("Y-m-d H:i:s").'=>'.json_encode($ret);  // 写入的内容
        $file = $path."weixin_".date("Ymd").".log";    // 写入的文件
        file_put_contents($file,$content,FILE_APPEND);  // 最简单的快速的以追加的方式写入写入方法，
//var_dump($ret);exit();

        $data = array();
        $data['order_no'] = $ret['out_trade_no'];
        $data['pay_type'] = 'weixin';
        $data['trade_no'] = $ret['transaction_id'];
        $data['total_fee'] = $ret['total_fee'];
        $total_fee=$ret['total_fee']/100;
        $result = Db::name('order')
            ->where(['order_no'=> $data['order_no']])
            ->update(['order_status'=>2]);
        $use=Db::name('member')->where(['program_openid'=>$ret['openid']])->field('member_id')->find();
        Db::name('accounts')
            ->insert(['member_id'=>$use['member_id'],'admin_id'=>1,'accounts_money'=>$total_fee,'business_way'=>1,'time_end'=>$ret['time_end']]);
        if (is_array($result)) {
            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml.="</xml>";
            echo $xml;
        }else{
            $contents = 'error => '.json_encode($result);  // 写入的内容
            $files = $path."error_".date("Ymd").".log";    // 写入的文件
            file_put_contents($files,$contents,FILE_APPEND);  // 最简单的快速的以追加的方式写入写入方法，
            echo 'fail';
        }
    }

    //签名
    public function MakeSign($arrary){
        //签名步骤一：按字典序排序数组参数
        ksort($arrary);
        $string = $this->ToUrlParams($arrary);

        return $string;
    }
    //构建字符串
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
}


